package com.sikaryofficial.knowledge.interceptor;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.sikaryofficial.common.core.constant.Constants.TRACE_FLAG;

/**
 * 全局跟踪id拦截器
 */
@Slf4j
@Component
public class TraceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String traceId = request.getHeader(TRACE_FLAG);
        if (CharSequenceUtil.isBlank(traceId)) {
            MDC.put(TRACE_FLAG, IdWorker.get32UUID());
        } else {
            MDC.put(TRACE_FLAG, traceId);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //调用结束后删除
        MDC.remove(TRACE_FLAG);
    }

}
